package com.example.demo.ShiroConfig;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * ClassName:shiroConfig
 * Package:com.example.demo.ShiroConfig
 * Description:
 *
 * @date:2019/12/13 9:06
 * @author:
 */
@Configuration
public class shiroConfig {
    /**
     * 创建ShiroFactoryBean
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")
                                  DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //添加shiro 的内置过滤器（实现权限相关的拦截）
        Map<String,String> filterMap = new LinkedHashMap<String,String>();

        //放行页面
        filterMap.put("/login","anon");
        filterMap.put("/index","anon");

        //授权拦截器
        filterMap.put("/user/**","perms[Admins]");


        filterMap.put("/**", "authc");
        //修改调整的登录页面
        shiroFilterFactoryBean.setLoginUrl("/tologin");
        //设置未授权页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/toError");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return shiroFilterFactoryBean;
    }



    /**
     * 创建DefaultwebSecurityManager
     */
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getSecurityManager(@Qualifier("myRealm") myRealm myRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联realm
        securityManager.setRealm(myRealm);
        return securityManager;
    }




    /**
     * 创建realm
     */
    @Bean(name = "myRealm")
    public myRealm getRealm(){
        return new myRealm();
    }
}
